<?php

namespace App\Models;

use App\Exceptions\ApiErrorException;
use App\Util\ArrayUtil;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class GoodsRentSpecValue extends BaseModel
{
    const KEY = 'spec_value_id';
    const TABLE = 'sp_goods_rent_spec_value';

    protected $table = self::TABLE;
    protected $primaryKey = self::KEY;
    protected $connection = 'mysql';

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $guarded = [];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];

    protected $appends = ['img_url'];

    /**
     * 关联规格组表
     * @return BelongsTo
     */
    public function spec(): BelongsTo
    {
        return $this->belongsTo('Spec');
    }

    public function getImgUrlAttribute()
    {
        if($this->image_id){
            return config('alipay.oss.imgHost').$this->image_id;
        }else{
            return '';
        }
    }


    /**
     * 规格值写入数据库并生成id
     * @param int $specId
     * @param array $valueList
     */
    public static function getNewValueList(int $specId, array $valueList): array
    {
        // 规格组名称合集
        $values = ArrayUtil::getArrayColumn($valueList, 'spec_value');
        // 获取到已存在的规格值
        $alreadyData = static::getListByValues($specId, $values);
        // 遍历整理新的规格集
        foreach ($valueList as $key => &$item) {
            $alreadyItem = ArrayUtil::getArrayItemByColumn($alreadyData, 'spec_value', $item['spec_value']);
            if (!empty($alreadyItem)) {
                // 规格值已存在的记录spec_value_id
                $item['spec_value_id'] = $alreadyItem['spec_value_id'];
            } else {
                // 规格值不存在的新增记录
                $result = self::add($specId, $item);
                $item['spec_value_id'] = $result['spec_value_id'];
            }
        }
        return $valueList;
    }

    /**
     * 根据规格组名称集获取列表
     * @param int $specId
     * @param array $values
     */
    private static function getListByValues(int $specId, array $values)
    {
        return (new static)->where('spec_id', '=', $specId)
            ->whereIn('spec_value', $values)
            ->select('spec_value_id','spec_value')->get();
    }

    /**
     * 新增规格值记录
     * @param int $specId
     * @param array $item
     */
    private static function add(int $specId, array $item)
    {
        return self::query()->create([
            'image_id' => isset($item['image_id'])?$item['image_id']:'',
            'spec_value' => $item['spec_value'],
            'spec_id' => $specId,
        ]);
    }


}
